package com.qf.zuulserver11000.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * 限流过滤器
 * @author q
 * @version V1.0
 * @date 2022/01/20
 **/
@Component
public class MyZuulFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER; //5
    }

    /**
     * 根据业务场景判断是否执行该过滤器
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        // 获取登录标识，有，则过滤。没有，直接中断
        if (StringUtils.isNotBlank((String) context.get("loginToken"))){
            System.out.println("MyZuulFilter --> 当前已登陆");
            return true;
        }
        System.out.println("MyZuulFilter --> 当前未登陆");
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        //当前请求上下文对象
        RequestContext context = RequestContext.getCurrentContext();

        //限流措施
        /*Long count = redisTemplate.opsForValue().increment("my-zuul-count");
        if (count == 1) {
            redisTemplate.expire("my-zuul-count",60, TimeUnit.SECONDS);
        }
        if (count > 6) {
            //限流，不放行
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(200);
            context.setResponseBody("request limited! Please try again later!");

        }else{
            //放行
            context.setSendZuulResponse(true);
        }*/
        System.out.println("MyZuulFilter run -->");
        return null;
    }
}
